<template>
  <ElCard>
    <div class="flex justify-start mb-5">
      <el-button class="mr-2" type="primary" @click="returnPage">返回</el-button>
      <el-button class="mr-2" type="primary" @click="saveProductionPlan(0)">保存</el-button>
      <el-button class="mr-2" type="primary" @click="saveProductionPlan(1)">保存并生效</el-button>
    </div>
    <div class="production-scheduling">
      <el-form class="flex flex-wrap justify-start" style="align-items: center;" label-width="120px">
        <el-form-item label="排产周期:">
          <el-select v-model="schedulingType" style="width: 100px" placeholder="请选择" @change="changeSchedulingType">
            <el-option v-for="item in schedulingTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="月份:" v-if="schedulingType === 'month'">
          <el-date-picker v-model="productionPlan.planMonth" type="month" placeholder="选择月份" format="YYYY-MM" value-format="YYYY-MM" @change="changeMonth"></el-date-picker>
        </el-form-item>
        <el-form-item label="计划日期:" v-if="schedulingType === 'day'">
          <el-date-picker style="width: 220px" v-model="productionPlan.planDate" type="date" placeholder="选择计划日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="planDayChange"></el-date-picker>
        </el-form-item>
        <el-form-item label="计划起始日期:" v-if="schedulingType === 'dateRange'">
          <el-date-picker style="width: 220px" v-model="productionPlan.planRangeDate" type="daterange" :clearable="false" start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="planDayRangeChange"></el-date-picker>
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model="productionPlan.remark" :rows="1" type="textarea" />
        </el-form-item>
      </el-form>
      <!-- 按钮-打开dialog -->
      <div class="scheduling-option">
        <el-button type="warning" @click="openOrderDialog" :icon="Plus">选择生产订单</el-button>
      </div>
      <el-table :data="materialList" border style="width: 100%; margin-top: 20px">
        <el-table-column prop="productionOrderNumber" label="生产订单" align="center" width="220"></el-table-column>
        <el-table-column prop="materialCode" label="物料编码" align="center" width="220"></el-table-column>
        <el-table-column prop="materialName" label="物料名称" align="center" width="220"></el-table-column>
        <el-table-column prop="orderQuantity" label="计划数量" align="center" width="160">
          <template #default="scope">
            <el-input-number v-model="scope.row.orderQuantity" :min="0" style="width:130px" placeholder="" class="quantity-input"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="schedulingQuantity" label="排产数量" align="center" width="100">
          <template #default="scope">
            {{ scope.row.schedulingQuantity }}
          </template>
        </el-table-column>
        <el-table-column label="生产车间" width="160" align="center">
          <template #header>
            <div class="flex justify-center items-center">
              <div style="color: #FF3030;">&nbsp*&nbsp</div>
              <div>生产车间</div>
            </div>
          </template>
          <template #default="scope">
            <el-select v-model="scope.row.workshop" placeholder="请选择车间">
              <el-option v-for="(item, index) in gridList" :key="index" :label="item.gname" :value="item.gid" />
            </el-select>
          </template>
        </el-table-column>

        <!-- 动态生成日期列 -->
        <el-table-column v-for="(dateString, index) in formattedDateColumns" :key="index" :prop="dateString" :label="dateString" width="160" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.scheduleQuantities[dateString]" :min="0" @change="inputScheduling(scope.row,index)" style="width:130px" placeholder="" class="quantity-input"></el-input-number>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <Button type="link" style="color:red;" @click="deleteRow(scope.$index)">删除</Button>
            <Button type="link" @click="openStockDialog(scope.row)">查看库存</Button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 选择生产订单弹窗 -->
      <el-dialog v-model="orderDialogVisible" title="选择生产订单" @close="dialogCancel_btn" :close-on-click-modal="false" width="80%">
        <el-table :data="orderList" v-loading="loadingDialog" @selection-change="handleSelectionChange" max-height="500">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="saleOrderCode" label="销售订单号"></el-table-column>
          <el-table-column prop="productionOrderNumber" label="生产订单号">
            <template #header>
              <table-header-filter label="生产订单号" :bind-data="dialogFormData.productionOrderNumber" type="input" filterField="productionOrderNumber" @change="filterChangeEvent"></table-header-filter>
            </template>
          </el-table-column>
          <el-table-column prop="instructionNumber" label="制令号"></el-table-column>
          <el-table-column prop="materialCode" label="物料编码">
            <template #header>
              <table-header-filter label="物料编码" :bind-data="dialogFormData.materialCode" type="input" filterField="materialCode" @change="filterChangeEvent"></table-header-filter>
            </template>
          </el-table-column>
          <el-table-column prop="materialName" label="物料名称">
            <template #header>
              <table-header-filter label="物料名称" :bind-data="dialogFormData.materialName" type="input" filterField="materialName" @change="filterChangeEvent"></table-header-filter>
            </template>
          </el-table-column>
          <el-table-column prop="materialType" label="物料类型"></el-table-column>
          <el-table-column prop="materialComp" label="物料单位"></el-table-column>
          <el-table-column prop="orderQuantity" label="计划数量"></el-table-column>
          <el-table-column prop="businessMan" label="销售员"></el-table-column>
        </el-table>
        <div class="block" style="display: flex; justify-content: flex-end">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 50, 100]" :total="total" layout="total, sizes, prev, pager, next" @size-change="sizeChangeEvent" @current-change="currentChangeEvent"></el-pagination>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="orderDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmOrderSelection">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 选择物料弹窗 -->
      <el-dialog v-model="materialDialogVisible" title="选择物料" @close="dialogCancel_btn2" width="80%">
        <div class="dialog-head" style="display: flex;">
          <el-form :inline="true" :model="dialogFormData2">
            <el-form-item label="物料名称">
              <el-input v-model="dialogFormData2.materialName" clearable placeholder="请输入物料名称"></el-input>
            </el-form-item>
            <el-form-item label="物料编码">
              <el-input v-model="dialogFormData2.materialCode" clearable placeholder="请输入物料编码"></el-input>
            </el-form-item>
            <!--            <el-form-item label="客户名称">-->
            <!--              <el-input v-model="dialogFormData2.customerName" clearable-->
            <!--                        placeholder="请输入客户名称"></el-input>-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="客户编码">-->
            <!--              <el-input v-model="dialogFormData2.customerCode" clearable-->
            <!--                        placeholder="请输入客户编码"></el-input>-->
            <!--            </el-form-item>-->
            <el-form-item>
              <el-button type="primary" @click="search_btn2">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="materialDialogList" v-loading="loadingDialog" @selection-change="handleSelectionChange2">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="materialCode" label="物料编码"></el-table-column>
          <el-table-column prop="materialName" label="物料名称"></el-table-column>
          <el-table-column prop="standard" label="物料规格"></el-table-column>
          <el-table-column prop="comp" label="单位"></el-table-column>
          <el-table-column prop="typeName" label="类型"></el-table-column>
          <!--          <el-table-column prop="customerCode" label="客户编码"></el-table-column>-->
          <!--          <el-table-column prop="personal" label="销售员"></el-table-column>-->
        </el-table>
        <div class="block" style="display: flex; justify-content: flex-end">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 50, 100]" :total="total" layout="total, sizes, prev, pager, next" @size-change="sizeChangeEvent2"
            @current-change="currentChangeEvent2"></el-pagination>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="materialDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmMaterialSelection">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 查看库存弹窗 -->
      <el-dialog v-model="stockDialogVisible" title="查看库存" @close="stockDialogVisible=false" width="50%">
        <el-table :data="stockList" v-loading="loadingDialog">
          <el-table-column prop="bom"></el-table-column>
          <el-table-column prop="materialCode" label="物料编码"></el-table-column>
          <el-table-column prop="materialName" label="物料名称"></el-table-column>
          <el-table-column prop="availableStock" label="可用库存"></el-table-column>
        </el-table>
      </el-dialog>
    </div>
  </ElCard>
</template>

<script setup>
import { onMounted, ref,unref } from "vue";
import {
  ElButton,
  ElCard,
  ElDatePicker,
  ElDialog,
  ElForm,
  ElSelect,
  ElFormItem,
  ElTable,
  ElTableColumn,
  ElInput,
  ElInputNumber,
  ElLoading,
  ElMessage,
  ElPagination,
  ElRadio,
  ElRadioGroup,
  ElRadioButton,
  ElOption
} from "element-plus";
import { Plus } from '@element-plus/icons-vue'
import { Button } from "ant-design-vue";
import { getGridApi, getSaleOrderApi, saveProductionPlanApi, getStockApi,listMaterialsApi} from "#/api/productionPlan/index.js";
import { reqProductOrderList } from "#/api/productionPlan/index.js";
import { useRoute, useRouter } from "vue-router";
import dayjs from "dayjs";
import TableHeaderFilter from "#/components/tableHeardFilter.vue";

// 排产类型（周/月）
const schedulingType = ref("day");
const schedulingTypeOptions = ref([
  {
    value: "day",
    label: "日",
  },
  {
    value: "month",
    label: "月",
  },
  {
    value:"dateRange",
    label:"日期区间"
  }
]);
const schedulingMethod = ref("order");
const month = ref(null);

const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 物料列表
const materialList = ref([]);
const productionPlan = ref({
  remark: "",
  type: 0,
  planDate: dayjs().format("YYYY-MM-DD"),
  planRangeDate:[],
  planMonth:""
});
const loadingDialog = ref(true);

// 销售订单列表
const orderList = ref([]);
const dialogFormData = ref({});

//物料弹窗列表
const materialDialogList = ref([]);
const dialogFormData2 = ref({});
//库存弹窗列表
const stockList = ref([]);
const dialogFormData3 = ref({});
//车间
const gridList = ref([]);

// 弹窗相关
const orderDialogVisible = ref(false);
const selectedOrders = ref([]);

// 弹窗相关
const materialDialogVisible = ref(false);
const selectedMaterials = ref([]);

// 弹窗相关
const stockDialogVisible = ref(false);

// 日期列（动态生成）
const dateColumns = ref([]);
const formattedDateColumns = ref([]); // 格式化后的日期列
const router = useRouter();
const route = useRoute();

// 返回事件
const returnPage = () => {
  router.push({ name: "productionPlanList" }); // 返回列表页
};

// 计算排产数量
function inputScheduling(row, index) {
  console.log("row", row);
  row.schedulingQuantity = Object.values(row.scheduleQuantities).reduce(
    (sum, current) => sum + current,
    0
  );
  console.log(row.schedulingQuantity);
}

// 切换排产周期
const changeSchedulingType = () => {
  if (schedulingType.value === "month" || schedulingType.value === "dateRange") {
    formattedDateColumns.value.splice(0, dateColumns.value.length);
    return;
  }
  generateDateColumns();
};
// 切换月份
const changeMonth = () => {
  console.log("月份", productionPlan.value.planMonth);
  generateDateColumns();
};
//切换日期
const planDayChange = () => {
  console.log("计划日期", productionPlan.value.planDate);
  generateDateColumns();
}
//切换日期区间
const planDayRangeChange = () => {
  const [startDate, endDate] = productionPlan.value.planRangeDate;
  const timeDiff = Math.abs(new Date(endDate).getTime() - new Date(startDate).getTime());
  const dayDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
  if(dayDiff > 30){
    productionPlan.value.planRangeDate = [];
    return ElMessage.info("日期区间不能超过30天");
  }
  generateDateColumns();
}
// 获取车间列表
const getGridList = async () => {
  await getGridApi().then((response) => {
    console.log("content", response.data.content);
    gridList.value = response.data.content;
  });
};

// 生成日期列
const generateDateColumns = () => {
  const { planDate,planMonth,planRangeDate } = unref(productionPlan);
  const columns = [];

  // 设置日期为当前日期加上指定的天数
  // today.setDate(today.getDate() + 30);
  if (schedulingType.value === "dateRange") {
    if(planRangeDate.length !== 2) return;
    const [startDate, endDate] = planRangeDate;
    const timeDiff = Math.abs(new Date(endDate).getTime() - new Date(startDate).getTime());
    const dayDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1;
    const start = new Date(startDate);
    for (let d = 0; d < dayDiff; d++) {
      columns.push(new Date(start));
      start.setDate(start.getDate() + 1);
    }
  } else if (schedulingType.value === "month") {
    const date = new Date(planMonth);
    const currentYear = date.getFullYear();
    const currentMonth = date.getMonth();
    console.log("月份2", currentYear, currentMonth);
    // 创建一个表示下个月第一天的日期对象
    const nextMonthStart = new Date(currentYear, currentMonth, 1);
    // 创建一个表示下下个月第一天的日期对象（用于获取下个月的最后一天）
    const nextMonthEnd = new Date(currentYear, currentMonth, 0);
    // 获取下个月的天数
    const daysInNextMonth = nextMonthEnd.getDate();
    // 按月生成下个月每一天的日期
    for (let i = 1; i <= daysInNextMonth; i++) {
      const currentDate = new Date(currentYear, currentMonth, i);
      columns.push(currentDate);
    }
  } else {
    const curDay = new Date(planDate);
    columns.push(curDay);
  }
  dateColumns.value = columns;
  formattedDateColumns.value = columns.map((date) => formatDate(date)); // 格式化日期为字符串

  // 清空之前的数据
  materialList.value.forEach((material) => {
    material.scheduleQuantities = {};
    material.schedulingQuantity = 0;
  });
  formattedDateColumns.value.forEach((date) => {
    materialList.value.forEach((num) => {
      num.scheduleQuantities[date] = 0;
    });
  });
};

// 打开订单选择弹窗
const openOrderDialog = () => {
  orderDialogVisible.value = true;
  getProductOrderList();
};
//查看库存弹窗
const openStockDialog = (row) => {
  stockDialogVisible.value = true;
  getStockList(row);
};

function getStockList(row) {
  loadingDialog.value = true;
  // 获取库存列表
  getStockApi({ materialCode: row.materialCode })
    .then((response) => {
      console.log("content", response.data);
      stockList.value = response?.data?.map((item) => {
        return {
          bom: "BOM",
          materialCode: item.materialFields?.code,
          materialName: item.materialFields?.name,
          availableStock: item.availableStock,
        };
      });
      console.log("stockList", stockList);
      stockList.value[0].bom = "";
      console.log("第一行", stockList.value[0]);
      loadingDialog.value = false;
    })
    .catch((error) => {
      loadingDialog.value = false;
      console.error("获取库存列表失败!", error);
    });
}
function getProductOrderList() {
  loadingDialog.value = true;
  const params = Object.fromEntries(
    Object.entries(dialogFormData.value).filter(
      ([key, value]) => value !== "" && value !== null && value !== undefined
    )
  );
  console.log(params);
  reqProductOrderList({ size: pageSize.value, page: currentPage.value, ...params })
    .then((response) => {
      orderList.value = response.data.content;
      total.value = response.data.totalElements;
      loadingDialog.value = false;
      console.log("获取生产订单列表!", response);
    })
    .catch((error) => {
      loadingDialog.value = false;
      console.log("获取销售订单列表失败!", error);
    });
}

function getMaterialList() {
  loadingDialog.value = true;
  const params = Object.fromEntries(
    Object.entries(dialogFormData2.value).filter(
      ([key, value]) => value !== "" && value !== null && value !== undefined
    )
  );
  // 使用 params 发起请求
  console.log("params", params); // 此时 params 中不包含值为空的字段
  listMaterialsApi({ size: pageSize.value, page: currentPage.value, ...params })
    .then((response) => {
      console.log("content", response.data.content);
      materialDialogList.value = response.data.content;
      total.value = response.data.totalElements;
      loadingDialog.value = false;
    })
    .catch((error) => {
      loadingDialog.value = false;
      console.error("获取物料列表失败!", error);
    });
}

function dialogCancel_btn() {
  orderDialogVisible.value = false;
  dialogFormData.value = {};
  currentPage.value = 1;
  pageSize.value = 10;
  total.value = 0;
}
function dialogCancel_btn2() {
  materialDialogVisible.value = false;
  dialogFormData2.value = {};
  currentPage.value = 1;
  pageSize.value = 10;
  total.value = 0;
}
function dialogCancel_btn3() {
  stockDialogVisible.value = false;
  dialogFormData3.value = {};
  currentPage.value = 1;
  pageSize.value = 10;
  total.value = 0;
}

function search_btn() {
  getProductOrderList();
}

function search_btn2() {
  getMaterialList();
}
function search_btn3() {
  getStockList();
}

function deleteRow(index) {
  materialList.value.splice(index, 1);
}

function sizeChangeEvent(val) {
  pageSize.value = val;
  getProductOrderList();
}

function currentChangeEvent(val) {
  currentPage.value = val;
  getProductOrderList();
}
function sizeChangeEvent3(val) {
  pageSize.value = val;
  getStockList();
}

function currentChangeEvent3(val) {
  currentPage.value = val;
  getSaleOrderList();
}

// 处理订单选择
const handleSelectionChange = (selection) => {
  selectedOrders.value = selection;
};

// 确认订单选择
const confirmOrderSelection = () => {
  console.log("selectOrder", selectedOrders.value);
  const mergedOrders = mergeOrdersByMaterialCode(selectedOrders.value);
  materialList.value.push(...mergedOrders);
  formattedDateColumns.value.forEach((date) => {
    materialList.value.forEach((num) => {
      num.scheduleQuantities[date] = 0;
    });
  });
  console.log("Merged Orders:", mergedOrders);
  console.log("Sale Order:", selectedOrders.value);
  dialogCancel_btn();
  orderDialogVisible.value = false;
};

//处理物料选择
function sizeChangeEvent2(val) {
  pageSize.value = val;
  getMaterialList();
}

function currentChangeEvent2(val) {
  currentPage.value = val;
  getMaterialList();
}

// 处理订单选择
const handleSelectionChange2 = (selection) => {
  selectedMaterials.value = selection;
};

// 确认订单选择
const confirmMaterialSelection = () => {
  console.log("selectedMaterials", selectedMaterials.value);
  const mergedOrders = mergeOrdersByMaterialCode(selectedMaterials.value);
  materialList.value.push(...mergedOrders);
  formattedDateColumns.value.forEach((date) => {
    materialList.value.forEach((num) => {
      num.scheduleQuantities[date] = 0;
    });
  });
  console.log("Merged Orders:", mergedOrders);
  console.log("Sale Order:", selectedMaterials.value);
  dialogCancel_btn2();
  materialDialogVisible.value = false;
};

// 根据 materialCode 合并 orderQuantity 的函数
function mergeOrdersByMaterialCode(orders) {
  const merged = {};
  // 遍历每个订单
  for (const order of orders) {
    const { materialCode, orderQuantity, materialName,saleOrderCode,productionOrderNumber,instructionNumber,materialComp,orderRequire,businessMan } = order;
    //** 如果 materialCode 已经存在，则累加 orderQuantity，否则初始化
    merged[materialCode] = {
      productionOrderNumber,
      orderQuantity: orderQuantity,
      materialCode,
      materialName,
      scheduleQuantities: {}, // 初始化 scheduleQuantities 对象
      saleOrderCode,
      instructionNumber,
      materialComp,
      orderRequire,
      businessMan
    };
  }

  // 将对象转换回数组
  return Object.values(merged);
}

// 格式化日期为字符串
const formatDate = (date) => {
  return date
    ? `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    : "";
};

// 组装接口参数
const assembleParams = (state) => {
  const today = new Date();
  // 获取当前时间作为计划时间
  const currentTime = new Date();
  const formattedCurrentTime = `${currentTime.getFullYear()}-${String(
    currentTime.getMonth() + 1
  ).padStart(2, "0")}-${String(currentTime.getDate()).padStart(
    2,
    "0"
  )} ${String(currentTime.getHours()).padStart(2, "0")}:${String(
    currentTime.getMinutes()
  ).padStart(2, "0")}:${String(currentTime.getSeconds()).padStart(2, "0")}`;
  // 初始化生产计划明细列表
  const productionPlanDetailList = [];

  // 遍历 materialList，提取每个物料的计划数据
  materialList.value.forEach((material) => {
    const {
      materialCode,
      materialName,
      orderQuantity,
      workshop,
      scheduleQuantities,
      schedulingQuantity,
      saleOrderCode,
      instructionNumber,
      materialComp,
      orderRequire,
      businessMan,
      productionOrderNumber
    } = material;

    // 获取物料的计划时间列表
    const planMaterialNumberList = [];
    console.log("material", material);
    console.log("scheduleQuantities", scheduleQuantities);
    for (const [dateString, quantity] of Object.entries(scheduleQuantities)) {
      if (quantity > 0) { // 只处理有计划数量的日期
        planMaterialNumberList.push({
          planTime: formatPlanTime(dateString),
          quantity
        });
      }
    }
    const planSchedulingList =  getSchedulingList(planMaterialNumberList,orderQuantity);

    // 如果有计划时间，则添加到明细列表
    if (planSchedulingList.length > 0) {
      const grid = gridList.value.find((item) => item.gid === workshop);
      productionPlanDetailList.push({
        materialCode,
        materialName,
        orderQuantity,
        schedulingQuantity,
        gripId: workshop,
        gripName: grid?.gname,
        productPlanMaterialNumberList:planSchedulingList,
        state,
        saleOrderCode,
        instructionNumber,
        productionOrderNumber,
        materialComp,
        orderRequire,
        businessMan
      });
    }
  });

  // 统计总物料数和总计划数量
  const materialNumber = productionPlanDetailList.length;
  const planQuantity = productionPlanDetailList.reduce((total, item) => {
    return (
      total +
      item.productPlanMaterialNumberList.reduce(
        (subTotal, subItem) => subTotal + subItem.quantity,
        0
      )
    );
  }, 0);

  return {
    remark: productionPlan.value.remark,
    materialNumber,
    planQuantity,
    completedQuantity: 0,
    productPlanMaterialList:productionPlanDetailList,
    state
  };
};

// 格式化计划时间
const formatPlanTime = (dateString) => {
  const [year, month, day] = dateString.split("-");
  return `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")}`;
};

// 保存按钮的点击事件
const saveProductionPlan = (state = 0) => {
  if (!materialList.value || materialList.value.length === 0) {
    ElMessage.info("没有要排产的物料");
    return;
  }
  let isPlannedValid = true; // 添加一个标志变量

  const current = materialList.value.find((item) => item.workshop == null);
  if (current) {
    // 如果找到匹配的批号
    isPlannedValid = false; // 设置标志为 false
  }

  if (!isPlannedValid) {
    ElMessage.info("请选择生产车间");
    return; // 如果标志为 false，直接返回，不执行后续代码
  }
  const loading = ElLoading.service({
    lock: true,
    text: "加载中...",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  const params = assembleParams(state);
  console.log("Assembled Params:", params);
  // 调用接口
  saveProductionPlanApi(params)
    .then((response) => {
      router.push({ name: "productionPlanList" }); // 返回列表页
      ElMessage.success("保存成功!");
    })
    .catch((error) => {
      ElMessage.error("保存失败!");
      console.error("保存失败:", error);
    })
    .finally(() => {
      loading.close();
    });
};

// 初始化日期列
onMounted(() => {
  generateDateColumns();
  getGridList();
});

//dialogFormData筛选
const filterChangeEvent = (parameter) => {
  const { state, filterField, selectedValue } = parameter;
  //清空操作
  if (state === 'clear') {
    if (dialogFormData.value[filterField] !== '') {
      dialogFormData.value[filterField] = '';
      search_btn();
    }
  }

  //确定操作
  if (state === 'confirm') {
    dialogFormData.value[filterField] = selectedValue;
    if (selectedValue !== '') {
      search_btn();
    }
  }
}

//处理排产累计数量
const getSchedulingList = (list,total) => {
  const sortedData = [...list].sort((a, b) => new Date(a.planTime) - new Date(b.planTime));
  let cumulativeQuantity = Number(total);

  return sortedData.map(item => {
    if (item.quantity <= cumulativeQuantity){
      cumulativeQuantity -= item.quantity;
    } else {
      cumulativeQuantity = 0;
    }
    return { ...item, cumulativeQuantity };
  });
}
</script>

<style scoped>
.production-scheduling {
  //padding: 20px;
}

.quantity-input {
  margin-left: 10px;
}

.demo-form-inline {
  display: flex;
  justify-content: space-between;
}
</style>
